<template>
    <graph-dialog
      :visible.sync="dialogVisible"
      @onClose="handleClose">
      <div class="graph-dialog">
        <div class="graph-dialog__content">
          <!-- 弹窗关闭按钮 -->
          <div class="graph-dialog__close">
            <i class="el-icon-close"></i>
          </div>

          <div
            ref="graphMain"
            v-loading="loading"
            element-loading-text="正在加载"
            class="graph-main">
            <div class="slider-box">
              <div class="graph-slider-pane">
                <el-slider class="graph-slider" v-model="noden" @change="onSliderNodeChange"></el-slider>
                <span class="demonstration">{{ sliderNodeText }}</span>
              </div>
              <div class="graph-slider-pane">
                <el-slider class="graph-slider" v-model="linksn" @change="onSliderLinksChange"></el-slider>
                <span class="demonstration">{{ sliderLinksText }}</span>
              </div>
            </div>

            <div id="container" style="width: 100%; height: 100%;"></div>
            <FlowSimilar ref="flowSimilar"/>
            <EntityInfo ref="entityInfo"/>
          </div>
        </div>
      </div>
    </graph-dialog>
</template>

<script>
import echarts from 'echarts'
import { getKnowlegeGraph } from '@/api/public'
import FlowSimilar from '@/components/FlowSimilar'
import EntityInfo from '@/components/EntityInfo/EntityInfo.vue'

export default {
  components: { GraphDialog: () => import('./GraphDialog'), FlowSimilar, EntityInfo },
  // components: { GraphDialog: () => import('./GraphDialog') },
  data() {
    return {
      neoids: [],
      category: '',
      dialogVisible: false,
      loading: false,
      graphData: null,
      // neoids: [],
      // category: '',
      noden: 100,
      linksn: 100,
      isShow: true,
      getBefore: {}, // 前一个界面传来的数据
      tableData: [],
      option: {
        series: []
      }
    }
  },
  computed: {
    sliderNodeText() {
      return `已显示 ${this.noden}% 的节点`
    },
    sliderLinksText() {
      return `每个节点最多显示 ${this.linksn}% 的连接`
    }
  },
  created() {},
  methods: {
    // 获取前一个界面传来的数据
    show(query) {
      let category = query.category
      let neoids = query.neoids
      // console.log(neoids)
      this.neoids = neoids
      this.category = category
      this.dialogVisible = true
      neoids = neoids.split(',')
      if (Array.isArray(neoids) && neoids.length > 0) {
        this.neoids = neoids
        this.getKnowlegeGraph()
        if (category) {
          this.$refs.flowSimilar.get(query)
          // this.$refs.entityInfo.get(neoids[0])
        }
      }
    },
    // 点击X，关闭图表，清除数据
    handleClose() {
      this.dialogVisible = false
      var myChart = null
      myChart = echarts.init(document.getElementById('container'))
      myChart.clear()
      this.$refs.flowSimilar.clear()
      this.$refs.entityInfo.clear()
    },
    // 读取图表数据
    getKnowlegeGraph() {
      this.loading = true
      let param = new URLSearchParams()
      // param.append('neoids', JSON.stringify(['9771', '54941', '55340', '22']))
      param.append('neoids', JSON.stringify(this.neoids))
      getKnowlegeGraph(param).then((res) => {
        // console.log(res)
        this.loading = false
        this.graphData = res
        this.refreshGraph('', res)
      })
    },
    refreshGraph(question, result) {
      var window_width = this.$refs.graphMain.offsetWidth
      var window_height = this.$refs.graphMain.offsetHeight
      var containerHeight = window_height
      var containerWidth = window_width
      var myChart = null

      const num = this.noden / 100
      const numm = this.linksn / 100
      let nums = parseInt(result.nodes.length * num)
      let linksnum = parseInt(result.links.length * numm)
      // 对mychart的初始化
      if (myChart) {
        myChart.clear()
      }
      myChart = echarts.init(document.getElementById('container'))

      // 刷新绘图页面
      var nodeSize = 80
      var dnodeSize = 19
      var fontSize = 14
      var nodes = []
      var links = []
      var categories = []
      var answerpath = result.answerpath
      var links_sum = 0

      result.nodes.forEach(function(node, index) {
        if (!categories.includes(node.category)) {
          categories.push({
            name: node.category
          })
        }
        // 确定节点形状
        node.symbol = 'circle'
        node.symbolSize = nodeSize - node.value * dnodeSize
        // 确定节点位置
        if (index === 497) {
          node.x = (containerWidth - nodeSize) / 2
          node.y = (containerHeight - nodeSize) / 2
          node.fixed = true
        } else {
          node.x = null
          node.y = null
        }
        // 初始化节点
        node.itemStyle = null
        node.label = {
          normal: {
            show: true,
            position: 'right'
          }
        }
        if (index < nums) {
          nodes.push(node)
        }
      })
      for (var i = 0; i < nodes.length; i++) {
        nodes[i].llength = 0
      }

      result.links.forEach(function(edge) {
        // 根据关系绘边
        if (nodes[edge.source] !== undefined && nodes[edge.target] !== undefined) {
          if (nodes[edge.source].llength < linksnum && nodes[edge.target].llength < linksnum) {
            links.push(edge)
            nodes[edge.source].llength = nodes[edge.source].llength + 1
            nodes[edge.target].llength = nodes[edge.target].llength + 1
          }
        }
      })

      // 点亮寻找的答案轨迹
      nodes.forEach(function(node) {
        if (answerpath.includes(node.id)) {
          node.itemStyle = {
            normal: {
              borderColor: 'yellow',
              borderWidth: 10
            }
          }
        }
      })
      links.forEach(function(link) {
        if ((answerpath.includes(link.source)) && (answerpath.includes(link.target))) {
          link.lineStyle = {
            normal: {
              color: 'yellow',
              width: 10
            }
          }
        }
      })
      for (let i = 0; i < result.links.length; i++) {
        if ((result.links[i].source < Math.floor(result.nodes.length * num)) && (result.links[i].target < Math.floor(result.nodes.length * num))) {
          links_sum = links_sum + 1
        }
      }
      const colorPalette = ['#E01F54', '#2980B9', '#009966', '#e05038', '#9fa8a3',
        '#89bdd3', '#e6af4b', '#d3758f', '#dcc392', '#2e4783',
        '#82b6e9', '#ff6347', '#a092f1', '#0a915d', '#7d4627',
        '#6699FF', '#ff6666', '#3cb371', '#d5b158', '#38b6b6'
      ]

      var option = {
        color: colorPalette,
        backgroundColor: 'rgba(0,0,0,0)',
        title: {
          text: result.answer,
          top: '1%',
          left: '1%',
          textStyle: {
            color: '#333333',
            fontSize: fontSize * 1.8,
            fontWeight: 'bolder'
          },
          subtext: '图中共有 ' + Math.floor(nodes.length) + ' 个节点以及 ' + links.length.toString() + ' 条关系',
          subtextStyle: {
            color: '#333333',
            fontSize: fontSize,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          formatter: function(params) {
            if (params.dataType === 'node') {
              return params.data.category
            } else {
              return params.data.name
            }
          }
        },
        legend: [{
          z: 0,
          data: categories,
          bottom: '1%',
          left: '1%',
          orient: 'vertical',
          itemGap: 12,
          selectedMode: false,
          textStyle: {
            color: '#333333',
            fontSize: fontSize * 0.9,
            fontWeight: 'bold'
          }
        }],
        series: [{
          type: 'graph',
          layout: 'force',
          data: nodes,
          links: links,
          zoom: 1.2,
          categories: categories,
          lineStyle: {
            normal: {
              color: 'source',
              width: 3,
              curveness: 0.2
            }
          },
          force: {
            repulsion: 1500,
            layoutAnimation: false
          },
          roam: true,

          focusNodeAdjacency: true,
          animationDuration: 2000
        }],
        textStyle: {
          fontFamily: '微软雅黑',
          fontSize: fontSize,
          fontWeight: 'bold'
        }
      }
      myChart.setOption(option)
      var TimeFn = null
      myChart.on('dblclick', (node) => {
        // console.log(node.data.neoId)
        clearTimeout(TimeFn)
        // this.$refs.entityInfo.show()
        this.$refs.entityInfo.get(node.data.neoId)
      })
      myChart.on('click', (node) => {
        // console.log(node)
        clearTimeout(TimeFn)
        let that = this
        TimeFn = setTimeout(function() {
          that.$refs.flowSimilar.mouseOver()
        }, 200)
      }) // myChart.on
    },
    onSliderNodeChange(val) {
      setTimeout(() => {
        this.refreshGraph('', this.graphData)
      }, 100)
    },
    onSliderLinksChange(val) {
      setTimeout(() => {
        this.refreshGraph('', this.graphData)
      }, 100)
    }
  }
}
</script>

<style lang="scss" scoped>
.graph-main {
  position: relative;
  height: 100%;
  width: 100%;
  background: #fff;
}

.slider-box {
  position: absolute;
  bottom: 10px;
  right: 20px;
  z-index: 999;
}

.graph-slider-pane {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 10px;
}

.graph-slider {
  width: 160px;
  padding: 10px;
  position: relative;
}
</style>
